// ---------------------------------------------------------------------
//
// -- 游戏基类包
// -- author £
//
// ---------------------------------------------------------------------

const CommonInfo = require('CommonInfo'),
    AppInfo = require('AppInfo'),
    Platform = require('Platform'),
    GameConfig = require('GameConfig'),
    Alert = require('Alert'),
    CommonUtil = require('CommonUtil'),
    superClass = require('singlebase').BaseSingleMediator,
    modelSuper = require('singlebase').BaseSingleModel;

const LOGIN_FAIL_STR = '登录异常，请尝试重连',
    RETRY_LS_SERVER_STR = '网络异常，请尝试重连。',
    NET_ERROR_SRT = '网络异常， 请稍后再试',
    GOTO_AUTH_STR = '登录游戏需要您同意用户信息授权。',
    LOAD_INFO_LOGIN = '正在登录用户',
    LOAD_INFO_CLICK_AUTH = '请点击屏幕授权';

let lobby_single_base = {
    //游戏中介层基类
    LobbySingleMediator: cc.Class({
        name: "LobbySingleMediator",
        extends: superClass,
        properties: {
        },

        initCtor: function () {
            CommonUtil.mysuper(superClass, this, 'initCtor');
            this._firstLogin = false;
        },

        clearData: function () {
            CommonUtil.mysuper(superClass, this, 'clearData');
            this._shareTicket = '';
            this._shareRCoinId = '';
            this._rCoinSender = 0;
            this._notShow = false;
        },

        resetData: function () {

        },

        onRegister: function (v) {
            CommonUtil.mysuper(superClass, this, 'onRegister', v);

            if (!AppInfo.wx) {
                if (require('SaveData').data) {
                    this.dealSaveData();
                    return;
                }
            }

            this.toLobbyScene();
            this.scene.switchSoundBtn(require('SoundInfo').getSEMute());

            if (!AppInfo.wx) return;

            let launchData = Platform.getLaunchData();

            if (launchData.shareTicket) {
                this._shareTicket = launchData.shareTicket;
            }

            if (launchData.query && launchData.query.shareRCoinId) {
                this._shareRCoinId = launchData.query.shareRCoinId;
                this._rCoinSender = launchData.query.rCoinSender;
            }
            
            CommonUtil.delay(
                this.scene.node,
                2,
                this._showGroupRank, this
            );
            Platform.startShare(
                (function () {
                    this._notShow = true;
                }).bind(this),
                (this._shareSuccess).bind(this)
            );
            Platform.onPlatformShow((this._platformShow).bind(this));
        },

        onShow: function () {
            CommonUtil.mysuper(superClass, this, 'onShow');

            if (AppInfo.wx) {
                if (!this._firstLogin) {
                    this.doLogin();
                } else {
                    this.doUpdateItem();
                    GameConfig.userProto.queryBest();
                }
            }
        },

        dealSaveData: function () {
            this.toGameScene();
        },

        onRelease: function () {
            CommonUtil.mysuper(superClass, this, 'onRelease');
            // CommonInfo.clearData();
            // require('TextureManager').release(this.textureKey);
            // this._scheduler.unscheduleAllCallbacks();
            // this._scheduler = null;
            // this._responseQueue.length = 0;
            // this._responseQueue = null;
            // this.model = null;
            // this.gameProtocol.clearData();
            // this.gameProtocol = null;
        },


        //-----------------------------------------------------------


        configData: function () {

        },

        /** 获取游戏状态 */
        gameState: function () {
            return this.model.gameState;
        },

        /** 显示总结算 */
        showTotalResult: function () {
        },

        _showGroupRank: function () {
            if (!this._shareTicket) return;

            this.groupRankHandler(this._shareTicket);
            this.scene.stopResultUpdate();
            this._shareTicket = '';
        },

        _platformShow: function (data) {
            console.log('_platformShow, _notShow', this._notShow);
            if (this._notShow) {
                this._notShow = false;
                return;
            }

            console.log(data);

            if (!require('MainMediator').isFree()) return;
            // if (CommonInfo.sceneState !== 0) return;

            if (data.shareTicket) {
                this._shareTicket = data.shareTicket;
            }

            if (data.query && data.query.shareRCoinId) {
                this._shareRCoinId = data.query.shareRCoinId;
                this._rCoinSender = parseInt(data.query.rCoinSender);
            }

            this._getRCoin();
            this._showGroupRank();
        },

        _shareSuccess: function (res) {
            // if (!require('MainMediator').isFree()) return;
            if (!res.shareTickets || !res.shareTickets.length) return;

            this._shareTicket = res.shareTickets[0];
            this._showGroupRank();
        },

        _getRCoin: function () {
            if (!CommonInfo.userRegisted) return;
            if (CommonInfo.self(this._rCoinSender)) return;
            if (!this._shareRCoinId || !this._rCoinSender) return;

            CommonInfo.shareRCoinId = this._shareRCoinId;
            this._shareRCoinId = '';
            this._rCoinSender = 0;
            GameConfig.userProto.getShareItem(
                (this.getRCoinReward).bind(this)
            );
        },

        _getConfig: function () {
            GameConfig.userProto.queryConfig(
                (this.getGameConfig).bind(this)
            );
            GameConfig.userProto.queryRecommandData(
                (this.getRecommandData).bind(this)
            );
        },

        _nextRecommand: function () {
            let icon = Platform.nextRecommand();

            if (!icon) return;

            this.scene.refreshMoreGameIcon(
                Platform.recommandIndex(),
                icon
            );
        },

        //-----------------------------------------------------------

        getRecommandData: function (xhrData) {
            if (xhrData.code) return;

            Platform.setRecommandData(xhrData.data.recommend_info);
            this._nextRecommand();
        },

        getGameConfig: function (xhrData) {
            if (xhrData.code) return;

            let data = xhrData.data,
                rCoinData = data.item_num_limits[0];

            CommonInfo.rCoinId = rCoinData.item_id;
            CommonInfo.totalRCoin = rCoinData.num_limit;
        },

        getRCoinReward: function (xhrData) {
            if (xhrData.code) return;

            CommonInfo.updateRCoinNum(
                parseInt(xhrData.data.item_reward.split(':')[1])
            );
            this.scene.updateRCoin(
                CommonInfo.getRCoinNum(),
                CommonInfo.totalRCoin,
                CommonInfo.shareRCoinCount
            );
        },

        clickAuthFinish: function () {
            this.inLoadData(true, 'server', LOAD_INFO_LOGIN);
        },

        requireClickAuth: function () {
            this.inLoadData(true, 'server', LOAD_INFO_CLICK_AUTH, 1);
        },

        gotoSetAuth: function () {
            this.inLoadData(false, 'server');
            Alert.show(null, GOTO_AUTH_STR, null,
                function () {
                    Platform.setAuth(
                        (function () {
                            GameConfig.userProto.getUserInfo();
                        }).bind(this),
                        (this.refuseAuth).bind(this)
                    )
                }, this
            );
        },

        loginFail: function () {
            this.inLoadData(false, 'server');
            Alert.show(null, LOGIN_FAIL_STR, null,
                this.doLogin, this
            );
        },

        doLogin: function () {
            this.inLoadData(true, 'server', LOAD_INFO_LOGIN);
            GameConfig.userProto.login();
        },

        refuseAuth: function () {
            this.loginFinish();
        },

        loginFinish: function (data) {
            console.log('loginFinish--------------------');
            this._firstLogin = true;
            // CommonInfo.userRegisted = false;
            // this.scene.loginFinish(CommonInfo.userInfo);
            // GameConfig.userProto.queryBest(CommonInfo.userID());
            this.inLoadData(false, 'server');
            this._getConfig();
            this._getRCoin();
            this.doUpdateItem();
            GameConfig.userProto.queryBest();

            if (require('SaveData').data) {
                this.dealSaveData();
                return;
            }
        },

        getRCoinDataFail: function () {
            this.inLoadData(false, 'server');
            Alert.show(null, NET_ERROR_SRT);
        },

        getRCoinData: function (xhrData) {
            if (xhrData.code) {
                this.getRCoinDataFail();
                return;
            }

            CommonInfo.setRCoinData(xhrData.data);
            GameConfig.userProto.queryItem(
                (this.getUserRCoinData).bind(this),
                (this.getRCoinDataFail).bind(this)
            );
        },

        getUserRCoinData: function (xhrData) {
            this.inLoadData(false, 'server');
            CommonInfo.setUserItems(xhrData.data);
            this.scene.updateRCoin(
                CommonInfo.getRCoinNum(),
                CommonInfo.totalRCoin,
                CommonInfo.shareRCoinCount
            );
            this.scene.showRCoinPanel();
        },

        doUpdateItem: function () {
            if (!CommonInfo.userRegisted) return;

            GameConfig.userProto.queryItem(
                (this.updateItemNum).bind(this),
            );
        },

        updateItemNum: function (xhrData) {
            if (xhrData.code) return;

            CommonInfo.setUserItems(xhrData.data);
            this.scene.updateRCoin(
                CommonInfo.getRCoinNum(),
                CommonInfo.totalRCoin,
                CommonInfo.shareRCoinCount
            );
        },

        //界面侦听-----------------------------------------------------------

        soundOnHandler: function () {
            require('SoundManager').setSoundMute(false);
            require('SoundManager').setSEMute(false);
            this.scene.switchSoundBtn(false);
        },

        soundOffHandler: function () {
            require('SoundManager').setSoundMute(true);
            require('SoundManager').setSEMute(true);
            this.scene.switchSoundBtn(true);
        },

        moreGameHandler: function () {
            this._notShow = true;
            Platform.previewImage();
            this._nextRecommand();
        },

        shareScoreHandler: function () {
            Platform.shareScore(
                (this._shareSuccess).bind(this)
            );
        },

        shareHandler: function () {
            this._notShow = true;
            Platform.share(
                (this._shareSuccess).bind(this)
            );
        },

        introRCoinHandler: function () {
            if (!CommonInfo.checkRegisted((this.getRCoinDataHandler).bind(this)))
                return;

            this.getRCoinDataHandler();
        },

        getRCoinDataHandler: function () {
            this.inLoadData(true, 'server');
            GameConfig.userProto.queryShareData(
                1,
                (this.getRCoinData).bind(this),
                (this.getRCoinDataFail).bind(this)
            );
        },  

        shareRCoinHandler: function () {
            this._notShow = true;
            this.scene.hideRCoinPanel();
            Platform.shareRCoin();
        },
    }),


    /** --------------------游戏模型基类--------------------------------------- */

    LobbySingleModel: cc.Class({
        extends: modelSuper,
        name: "LobbySingleModel",
        properties: {
        },

        // clearData: function () {
        //     CommonUtil.mysuper(modelSuper, this, 'clearData');
        // },

        // resetData: function () {
        //     CommonUtil.mysuper(modelSuper, this, 'resetData');

        // },

    }),
};

module.exports = lobby_single_base;